package com.cooljie.spring.dao;

import com.cooljie.spring.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by ACER on 2017/10/26.
 */
@Repository("jdbcUserDao")
public class IUserDaoImpl implements IUserDao {
    private JdbcTemplate jdbcTemplate;

    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }



    @Override
//    添加用户
    public void add(User user) {
        this.jdbcTemplate.update(
                "insert into t_user (username, password,nickname) values (?,?,?)",
                user.getUserName(), user.getPassword(), user.getNickName());
    }

    @Override
//    更新用户
    public void update(User user) {
        this.jdbcTemplate.update( "update t_user set username = ?,password=?,nickname=?  where id = ?",
                user.getUserName(), user.getPassword(), user.getNickName(), user.getId());

    }

    @Override
//    删除用户
    public void delete(int id) {
this.jdbcTemplate.update(
        "delete from t_user where id = ?",id);
    }

    @Override
//    查找单个用户
    public User load(int id) {
        User user=jdbcTemplate.queryForObject("select * from t_user where id=?",
                new UserRowMapper(),id);
        return user;
    }

    @Override
//    查询多个用户
    public List<Map<String, Object>> loadMore() {
         List users=jdbcTemplate.query("select * from t_user",new UserRowMapper());
        return users;
    }


    //返回查询结果对象
   public class UserRowMapper implements RowMapper<User> {

        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user=new User(
                    rs.getString("username"),
                    rs.getString("password"),
                    rs.getString("nickName")
            );
            user.setId(rs.getInt("id"));
            return user;
        }
    }

}
